package com.geekstudy.week11;

import redis.clients.jedis.Jedis;

public class RedisLockService {

    private final String REDIS_LOCK_PREFIX = "lock_"; // 锁的前缀
    private Jedis jedis;
    // private final UUIDTool uuidTool = new UUIDTool();

    public RedisLockService(Jedis jedis) {
        this.jedis = jedis;
    }

    /**
     * 获取锁
     * @param lockName 锁名称, 建议使用含义明确的字母组成的字符串
     * @param version 锁版本
     * @return
     */
    public boolean lock(String lockName, String version) {
        boolean lockStatus = false;
        String redisLockName = redisLockName(lockName);


        // String version = uuidTool.uuid();
        String getValue = jedis.get(redisLockName);
        if(getValue == null ) {
            jedis.setnx(redisLockName, version);
            String confirmVersion = jedis.get(redisLockName);
            if(confirmVersion != null && confirmVersion.equals(version)) {
                lockStatus = true;
            }
        }

        return lockStatus;
    }

    /**
     * 释放锁
     * @param lockName 锁名称
     * @param version 锁版本, 使用获取锁成功的 version, 才能释放
     * @return
     */
    public boolean releaseLock(String lockName, String version) {
        boolean success = false;
        String redisLockName = redisLockName(lockName);
        String value = jedis.get(redisLockName);
        if(version != null && version.equals(value)) {
            jedis.del(redisLockName);
            success = true;
        }
        return success;
    }




    private String redisLockName(String lockName) {
        if(lockName == null || lockName.isEmpty()) {
            lockName = "";
        }
        String redisLockName = REDIS_LOCK_PREFIX + lockName;
        return redisLockName;
    }
}
